package com.health.viewscontrols.medical.device.bo;

import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.health.httpbean.model.PoModel;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.leadron.library.BODevicePodType;
import com.leadron.library.BO_POD;
import com.leadron.library.IOReaderSender;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;

import java.util.List;

public class BOKrkActivity2 extends BaseDeviceActivity {

    public final static String UUID_SERVICE = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
    public final static String UUID_NOTIFY ="6e400003-b5a3-f393-e0a9-e50e24dcca9e";
    public final static String UUID_WRITE = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";

    BO_POD mBO_pod;
    BleDevice mBleDevice;
    private String mBloodOxygen;//血氧值
    private String mHeartRate;//心率值
    private String resultStringCH;//脉搏节律未见异常
    BleWriteCallback mBleWriteCallback = new BleWriteCallback() {
        @Override
        public void onWriteSuccess(int i, int i1, byte[] bytes) {
        }

        @Override
        public void onWriteFailure(BleException e) {
        }
    };

    BleNotifyCallback mBleNotifyCallback = new BleNotifyCallback() {
        @Override
        public void onNotifySuccess() {
        }

        @Override
        public void onNotifyFailure(BleException e) {
        }

        @Override
        public void onCharacteristicChanged(byte[] bytes) {
            if (mBO_pod != null) mBO_pod.toAdd(bytes);
        }
    };

    BleGattCallback mBleGattCallback = new BleGattCallback() {
        @Override
        public void onStartConnect() {
            Log.e("TAG", "onStartConnect: ");
            blueToothState.setText("蓝牙开始连接");
            showProgressDialog("正在连接" + deviceEnum.getTitle() + "设备");
        }

        @Override
        public void onConnectFail(BleDevice bleDevice, BleException e) {
            Log.e("TAG", "onConnectFail: " + e.toString());
            blueToothState.setText("蓝牙连接失败");
            cancelProgressDialog();
            if (mBleDevice != null) {
                BleManager.getInstance().connect(mBleDevice, mBleGattCallback);
            }
        }

        @Override
        public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt bluetoothGatt, int i) {
            Log.e("TAG", "onConnectSuccess: ");
//            BleManager.getInstance().notify(bleDevice, mBO_pod.getUUID_SERVICE(), mBO_pod.getUUID_NOTIFY_CCHARACTERISTIC(), mBleNotifyCallback);
            BleManager.getInstance().notify(bleDevice, UUID_SERVICE, UUID_NOTIFY, mBleNotifyCallback);
            blueToothState.setText("蓝牙连接成功");
            showProgressDialog("蓝牙连接成功，请按照设备计时器测量30秒出结果");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SystemClock.sleep(2000);
                    if (mBO_pod != null) mBO_pod.openParam();

                    SystemClock.sleep(1000);
                    if (mBO_pod != null) mBO_pod.openWave();

                    SystemClock.sleep(2000);
                    if (mBO_pod != null) mBO_pod.searchDeviceVersion();  // 查询版本 适用于
                }
            }).start();

        }

        @Override
        public void onDisConnected(boolean b, BleDevice bleDevice, BluetoothGatt bluetoothGatt, int i) {
            Log.e("TAG", "onDisConnected: " + b);
            blueToothState.setText("蓝牙连接断开");
            cancelProgressDialog();
            BleManager.getInstance().stopNotify(bleDevice, UUID_SERVICE, UUID_NOTIFY);
//            setStatusPre();
        }
    };

    @Override
    public void startDevice() {
        showProgressDialog("正在搜索" + deviceEnum.getTitle() + "设备");
        if (mBleDevice == null) {
            BleManager.getInstance().scan(new BleScanCallback() {
                @Override
                public void onScanFinished(List<BleDevice> list) {
                }

                @Override
                public void onScanStarted(boolean b) {
                }

                @Override
                public void onScanning(BleDevice bleDevice) {
                    Log.e("TAG", "onScanning: " + bleDevice.getName() + bleDevice.getMac());
                    if (bleDevice.getMac().equals(deviceEnum.getMac())) {
                        BleManager.getInstance().cancelScan();
                        mBleDevice = bleDevice;
                        BleManager.getInstance().connect(mBleDevice, mBleGattCallback);
                    }
                }
            });
        } else {
            BleManager.getInstance().connect(mBleDevice, mBleGattCallback);
        }
    }

    @Override
    public void doBusiness() {
        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 15000)
                .setConnectOverTime(20000)
                .setOperateTimeout(15000);

        tv_operation_tips.setText(com.nova.health.ble.R.string.bo_pc_60f);
        mBO_pod = new BO_POD(new BO_POD.BO_PODCallback() {
            @Override
            public void onGetSpO2Param(String nSpO2, String nPR, String fPI, boolean bProbe, String nPower) {
                String msg = String.format("nSpO2: %s nPR: %s fPI: %s bProbe: %b nPower: %s", nSpO2, nPR, fPI, bProbe, nPower);
                Log.e("TAG", msg);
                showMsg(nSpO2, nPR);
            }

            @Override
            public void onGetSpO2Wave(int wave, int flag, int pulse) {
//                String msg = String.format("wave: %d flag: %d pulse: %d", wave, flag, pulse);
//                Log.e("TAG", msg);
//                showMsg(msg);
            }

            @Override
            public void onGetDeviceVer(String softVer, String hardVer, String sn) {
//                String msg = String.format("softVer: %s hardVer: %s productName: %s", softVer, hardVer, sn);
//                Log.e("TAG", msg);
//                showMsg(msg);
            }

            @Override
            public void onWorkingStatus(int mode, int step, int para1, int para2, int resultCode, String resultStringCH, String resultStringEN) {
                if (!TextUtils.isEmpty(resultStringCH)) {
                    BOKrkActivity2.this.resultStringCH = resultStringCH;
                    showResultState(resultStringCH);
                }
//                String msg = String.format("mode: %d step: %d para1: %d para2: %d resultCode: %d resultStringCH: %s resultStringEN: %s", mode, step, para1, para2, resultCode, resultStringCH, resultStringEN);
//                Log.e("TAG", msg);
//                showMsg(msg);
            }

            @Override
            public void onSP20TempValue(int tempUnit, String value) {
//                String msg = String.format("tempUnit: %d value: %s", tempUnit, value);
//                Log.e("TAG", msg);
//                showMsg(msg);
            }

            @Override
            public void onAP20Wave(int flow, int snore) {
//                String msg = String.format("onAP20Wave:flow: %d snore: %d", flow, snore);
//                Log.e("TAG", msg);
//                showMsg(msg);
            }

            @Override
            public void onAP20Params(int rr, int singleFlag) {
//                String msg = String.format("onAP20Params:rr: %d", rr);
//                Log.e("TAG", msg);
            }
        }, new IOReaderSender() {
            @Override
            public int toRead(byte[] bytes) {
                return 0;
            }

            @Override
            public void toSend(byte[] bytes) {
                if (mBleDevice != null) {
//                    BleManager.getInstance().write(mBleDevice, mBO_pod.getUUID_SERVICE(), mBO_pod.getUUID_WRITE_CHARACTERISTIC(), bytes, mBleWriteCallback);
                    BleManager.getInstance().write(mBleDevice, UUID_SERVICE, UUID_WRITE, bytes, mBleWriteCallback);
                }
            }
        });

        mBO_pod.setDeviceType(BODevicePodType.BODevicePodType_60F);
        mBO_pod.toStart();

        startDevice();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mBleDevice == null) {
                    disconnectDevice();
                }
            }
        },4000);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mBleDevice == null) {
                    disconnectDevice();
                    startDevice();
                }
            }
        },5500);
    }

    @Override
    public void update(String hexStr) {
    }

    private void setStatusPre() {
//        tv_state.setText("获取测量结果成功");
        tv_result.setText("脉率:" + mHeartRate + "bpm\t\t" + "血氧:" + mBloodOxygen + "%");
        Log.e(TAG, "setStatusPre: " + mBloodOxygen + "/" + mHeartRate);
        if (!TextUtils.isEmpty(mBloodOxygen)) {
            DeviceShowSaveData.getDataShow(mBloodOxygen + "/" + mHeartRate, BluetoothConstant.XUEYANG_LIKANG_KRK);
        }
    }

    @Override
    public void disconnectDevice() {
        try {
            BleManager.getInstance().cancelScan();
            if (mBleDevice != null) BleManager.getInstance().disconnect(mBleDevice);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void showMsg(String nSpO2, String nPR) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mBloodOxygen = nSpO2;
                mHeartRate = nPR;
                tv_state.setText("实时测量数据：");
                tv_result.setText("脉率:" + mHeartRate + "bpm\t\t" + "血氧:" + mBloodOxygen + "%");
            }
        });
    }

    private void showResultState(String resultStringCH) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                cancelProgressDialog();
                tv_state.setText("测试结果:" + resultStringCH);
                tv_result.setText("脉率:" + mHeartRate + "bpm\t\t" + "血氧:" + mBloodOxygen + "%");
                Log.e(TAG, "setStatusPre: " + mBloodOxygen + "/" + mHeartRate);
                if (!TextUtils.isEmpty(mBloodOxygen)) {
                    DeviceShowSaveData.getDataShow(mBloodOxygen + "/" + mHeartRate, BluetoothConstant.XUEYANG_LIKANG_KRK);
                    PoModel poModel = new PoModel();
                    poModel.setBloodOxygenSaturation(mBloodOxygen + "");
                    poModel.setHeartRate(mHeartRate + "");
                    DeviceShowSaveData.saveXueyang(GsonUtils.toJson(poModel));
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBleDevice != null) {
            BleManager.getInstance().stopNotify(mBleDevice, UUID_SERVICE, UUID_NOTIFY);
            //断开设备
            BleManager.getInstance().disconnect(mBleDevice);
        }
        try {
            BleManager.getInstance().cancelScan();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mBO_pod != null) {
            mBO_pod.toStop();
            mBO_pod = null;
        }
    }

}
